/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { ctx2 } from '@app-cad/module';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useMemo, useState } from 'react';
import { ChildCommandProps } from './type';

type FormData = {
  curve1?: pickedLineData;
  curve2?: pickedLineData;
};

type Params = {
  curve1: string;
  curve2: string;
  solution: number;
};

// 线线相交
export function CommandCurveIntersection({
  onClose,
  props,
  editDxid,
}: ChildCommandProps) {
  const [formData, setFormData] = useState<FormData>({});

  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({});
      return;
    }

    const params: Params = props.params;
    const { curve1, curve2, solution: paramSolution } = params;

    await initEditDependency([curve1, curve2]);

    setFormData({
      curve1: picker.generatePickObjByPickID(curve1) as pickedLineData,
      curve2: picker.generatePickObjByPickID(curve2) as pickedLineData,
    });

    setSolution(paramSolution);
  }, [editDxid]);

  const isFormDataValid = () => {
    const { curve1, curve2 } = formData;

    return curve1 != null && curve2 != null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-curve-intersection', {
      commandName: 'CreateVertex',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { curve1, curve2 } = formData;

    return confirmCommand(
      {
        a: {
          mode: 'curve-int',
          curve1: curve1.edgeId,
          curve2: curve2.edgeId,
          solution,
        } as Params,
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();

      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);

    ctx2.viewer.requestRender();
  };

  useEffect(() => {
    const { curve1, curve2 } = formData;
    if (curve1 != null && curve2 != null && curve1.edgeId === curve2.edgeId) {
      setFormData({});
      MessageTip.warning(`不允许选择相同曲线`);
      // 比较好的做法是不让用户 选择相同的曲线
      // 即在用户尝试选择相同曲线时提示并禁止用户做选择。
      return;
    }

    preview();
  }, [formData]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve1: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      curve2: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      solution: MULTI_SOLUTION_SCHEMA,
    },
  };

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      className='-mt-3'
      onCancel={onClose}
      schema={schema}
      formData={finalFormData}
      submitLoading={isLoading}
      isFormDataValid={isFormDataValid()}
      onChange={(v) => {
        setFormData(v);
        setSolution(v.solution[0]);
      }}
      extraUiSchema={{
        curve1: {
          'ui:placeholder': '请输入曲线1',
          'ui:autofocus': true,
          'ui:options': {
            allowInfiniteLine: true,
          },
        },
        curve2: {
          'ui:placeholder': '请输入曲线2',
          'ui:options': {
            allowInfiniteLine: true,
          },
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}
